<template>
  <div class="resource-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>资源管理</h1>
      <p class="subtitle">查看和管理所有上传资源</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <div class="filter-section">
        <div class="search-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索资源名称或描述"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="正常" value="1" />
            <el-option label="删除" value="0" />
            <el-option label="封禁" value="2" />
          </el-select>
          
          <el-select v-model="categoryFilter" placeholder="分类筛选" style="width: 120px" @change="handleFilter">
            <el-option label="全部分类" value="" />
            <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
          
          <el-select v-model="typeFilter" placeholder="文件类型" style="width: 140px" @change="handleFilter">
            <el-option label="全部类型" value="" />
            <el-option v-for="fileType in fileTypeList" :key="fileType" :label="fileType" :value="`.${fileType}`" />
          </el-select>
          
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 资源列表 -->
    <el-card class="table-card">
      <el-table
        :data="resources"
        v-loading="loading"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'uploadTime', order: 'descending' }"
      >
        <el-table-column prop="id" label="ID" width="65" sortable />
        
        <el-table-column label="预览" width="70">
          <template #default="scope">
            <div class="resource-preview">
              <el-icon v-if="scope.row.fileType === '.pdf'" size="40" color="#409eff">
                <Document />
              </el-icon>
              <el-icon v-else-if="['.jpg', '.jpeg', '.png', '.gif'].includes(scope.row.fileType)" size="40" color="#67c23a">
                <Files />
              </el-icon>
              <el-icon v-else-if="['.mp4', '.avi', '.mov'].includes(scope.row.fileType)" size="40" color="#e6a23c">
                <VideoPlay />
              </el-icon>
              <el-icon v-else-if="['.mp3', '.wav'].includes(scope.row.fileType)" size="40" color="#f56c6c">
                <Headset />
              </el-icon>
              <el-icon v-else size="40" color="#909399">
                <Files />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="文件名" width="100" show-overflow-tooltip>
          <template #default="scope">
            <div class="resource-name" @click="viewResourceDetail(scope.row)">
              {{ scope.row.title || scope.row.description || '未命名文件' }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="上传者" width="120">
          <template #default="scope">
            {{ scope.row.userName || scope.row.nickname || '未知用户' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="fileType" label="类型" width="100">
          <template #default="scope">
            <el-tag size="small" :type="getFileTypeTagType(scope.row.fileType)">
              {{ scope.row.fileType }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="fileSize" label="大小" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success" size="small">正常</el-tag>
            <el-tag v-else-if="scope.row.status === 0" type="danger" size="small">删除</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning" size="small">封禁</el-tag>
            <el-tag v-else type="info" size="small">未知</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="downloadCount" label="下载次数" width="110" sortable />
        
        <el-table-column prop="createdAt" label="上传时间" width="160" sortable>
          <template #default="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewResourceDetail(scope.row)"
            >
              查看详情
            </el-button>
            
            <el-button
              type="info"
              size="small"
              @click="downloadResource(scope.row)"
            >
              下载
            </el-button>
            
            <el-button
              v-if="scope.row.status === 1"
              type="danger"
              size="small"
              @click="toggleResourceStatus(scope.row, 0)"
            >
              删除
            </el-button>
            
            <el-button
              v-if="scope.row.status === 1"
              type="warning"
              size="small"
              @click="toggleResourceStatus(scope.row, 2)"
            >
              封禁
            </el-button>
            
            <el-button
              v-else-if="scope.row.status === 0 || scope.row.status === 2"
              type="success"
              size="small"
              @click="toggleResourceStatus(scope.row, 1)"
            >
              恢复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 资源详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="资源详情" width="700px" top="5vh">
      <div v-if="selectedResource" class="resource-detail">
        <div class="detail-header">
          <div class="resource-icon">
            <el-icon v-if="selectedResource.fileType === '.pdf'" size="80" color="#409eff">
              <Document />
            </el-icon>
            <el-icon v-else-if="['.jpg', '.jpeg', '.png', '.gif'].includes(selectedResource.fileType)" size="80" color="#67c23a">
              <Files />
            </el-icon>
            <el-icon v-else-if="['.mp4', '.avi', '.mov'].includes(selectedResource.fileType)" size="80" color="#e6a23c">
              <VideoPlay />
            </el-icon>
            <el-icon v-else-if="['.mp3', '.wav'].includes(selectedResource.fileType)" size="80" color="#f56c6c">
              <Headset />
            </el-icon>
            <el-icon v-else size="80" color="#909399">
              <Files />
            </el-icon>
          </div>
          <div class="resource-info">
            <h3>{{ selectedResource.title || selectedResource.description || '未命名文件' }}</h3>
            <p>上传者：{{ selectedResource.userName || selectedResource.nickname || '未知用户' }}</p>
            <p>上传时间：{{ formatTime(selectedResource.createdAt) }}</p>
          </div>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="资源ID">{{ selectedResource.id }}</el-descriptions-item>
          <el-descriptions-item label="文件类型">
            <el-tag :type="getFileTypeTagType(selectedResource.fileType)">
              {{ selectedResource.fileType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">{{ formatFileSize(selectedResource.fileSize) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="selectedResource.status === 1" type="success">正常</el-tag>
            <el-tag v-else-if="selectedResource.status === 0" type="danger">删除</el-tag>
            <el-tag v-else-if="selectedResource.status === 2" type="warning">封禁</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下载次数">{{ selectedResource.downloadCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="点赞次数">{{ selectedResource.likeCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ getCategoryName(selectedResource.categoryId) }}</el-descriptions-item>
          <el-descriptions-item label="上传用户ID">{{ selectedResource.userId }}</el-descriptions-item>
          <el-descriptions-item label="文件路径" :span="2">
            <el-input v-model="selectedResource.fileUrl" readonly />
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ selectedResource.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="resource-actions">
          <el-button type="primary" @click="downloadResource(selectedResource)">
            <el-icon><Download /></el-icon>
            下载文件
          </el-button>
          
          <el-button
            v-if="selectedResource.status === 1"
            type="danger"
            @click="toggleResourceStatus(selectedResource, 0)"
          >
            删除资源
          </el-button>
          
          <el-button
            v-if="selectedResource.status === 1"
            type="warning"
            @click="toggleResourceStatus(selectedResource, 2)"
          >
            封禁资源
          </el-button>
          
          <el-button
            v-else-if="selectedResource.status === 0 || selectedResource.status === 2"
            type="success"
            @click="toggleResourceStatus(selectedResource, 1)"
          >
            恢复资源
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Document, VideoPlay, Headset, Files, Download } from '@element-plus/icons-vue'
import { getAllResources, changeResourceState, type ResourceDetailVO } from '../../api/admin'

// 数据定义
const resources = ref<ResourceDetailVO[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索和筛选
const searchQuery = ref('')
const statusFilter = ref('')
const typeFilter = ref('')
const categoryFilter = ref('')

// 对话框
const detailDialogVisible = ref(false)
const selectedResource = ref<ResourceDetailVO | null>(null)

// 分类列表
const categoryList = ref([
  { id: 1, name: '文档' },
  { id: 2, name: '课件' },
  { id: 3, name: '试卷' },
  { id: 4, name: '其他' }
])

// 文件类型列表
const fileTypeList = ref(['pdf', 'docx', 'pptx', 'xlsx', 'zip', 'doc', 'md', '其他'])

// 获取资源列表
const fetchResources = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1, // 后端页码从0开始
      size: pageSize.value,
      ...(categoryFilter.value && { categoryId: Number(categoryFilter.value) }),
      ...(typeFilter.value && { fileType: typeFilter.value }),
      ...(statusFilter.value && { state: Number(statusFilter.value) })
    }
    
    const result = await getAllResources(params)
    console.log('获取资源列表结果:', result)
    if (result.code === 200) {
      resources.value = result.data.records
      total.value = result.data.total
    } else {
      ElMessage.error(result.message || '获取资源列表失败')
    }
  } catch (error) {
    console.error('获取资源列表失败:', error)
    ElMessage.error('获取资源列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 重新获取数据，搜索功能暂时通过重新加载实现
  currentPage.value = 1
  fetchResources()
}

// 筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchResources()
}

// 刷新数据
const refreshData = () => {
  fetchResources()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchResources()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchResources()
}

// 查看资源详情
const viewResourceDetail = (resource: any) => {
  selectedResource.value = resource
  detailDialogVisible.value = true
}

// 下载资源
const downloadResource = (resource: ResourceDetailVO) => {
  if (resource.fileUrl) {
    // 创建一个临时的 a 标签来触发下载
    const link = document.createElement('a')
    link.href = resource.fileUrl
    link.download = resource.title || `resource_${resource.id}${resource.fileType}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success(`开始下载：${resource.title || '未命名文件'}`)
  } else {
    ElMessage.warning('文件链接不存在，无法下载')
  }
}

// 切换资源状态
const toggleResourceStatus = async (resource: ResourceDetailVO, newStatus: number) => {
  const statusText = newStatus === 1 ? '恢复' : newStatus === 0 ? '删除' : '封禁'
  
  try {
    await ElMessageBox.confirm(
      `确定要${statusText}资源《${resource.title || resource.description || '未命名文件'}》吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const result = await changeResourceState({
      resourceId: resource.id,
      state: newStatus
    })
    
    if (result.code === 200) {
      ElMessage.success(`资源${statusText}成功`)
      // 重新获取数据以更新状态
      fetchResources()
      
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false
      }
    } else {
      ElMessage.error(result.message || `资源${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改资源状态失败:', error)
      ElMessage.error(`资源${statusText}失败`)
    }
  }
}

// 获取文件类型标签类型
const getFileTypeTagType = (fileType: string) => {
  if (!fileType) return ''
  const type = fileType.toLowerCase()
  if (['.pdf', '.doc', '.docx'].includes(type)) return 'primary'
  if (['.jpg', '.jpeg', '.png', '.gif'].includes(type)) return 'success'
  if (['.mp4', '.avi', '.mov'].includes(type)) return 'warning'
  if (['.mp3', '.wav'].includes(type)) return 'info'
  if (['.zip', '.rar', '.7z'].includes(type)) return 'danger'
  return ''
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categoryList.value.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '未知'
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchResources()
})
</script>

<style scoped>
.resource-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  color: #2c3e50;
  font-size: 2rem;
  margin-bottom: 8px;
  font-weight: 600;
}

.subtitle {
  color: #7f8c8d;
  font-size: 1rem;
  margin: 0;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  overflow: hidden;
}

.resource-preview {
  display: flex;
  align-items: center;
  justify-content: center;
}

.resource-name {
  color: #409eff;
  cursor: pointer;
  font-weight: 500;
}

.resource-name:hover {
  text-decoration: underline;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.resource-detail {
  padding: 16px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.resource-icon {
  margin-right: 16px;
}

.resource-info h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.resource-info p {
  margin: 4px 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.resource-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-image) {
  border-radius: 4px;
}
</style>
